package cn.edu.niit.servlet;

import cn.edu.niit.javabean.Book;
import cn.edu.niit.service.BookService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "SearchBooksServlet", urlPatterns = "/book/search")
public class SearchBooksServlet extends HttpServlet {

    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp) throws ServletException, IOException {
        //1. 取参（req当前的页码, 每页的数量, 搜索）
//        String paramJson = IOUtils.toString(
//                req.getInputStream(), "UTF-8");
//        HashMap<String, Object> parseObject =
//                JSON.parseObject(paramJson,
//                        HashMap.class);
        //fs layui传 application/x-www-form-urlencoded 需解析
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                params.put(entry.getKey(), entry.getValue()[0]);
            }
        }
        int pageNum = Integer.parseInt((String) params.get("pageNum"));
        int pageSize =Integer.parseInt((String) params.get("pageSize"));
        String param = (String) params.get("search");
        HttpSession session = req.getSession();
        List<Book> books = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> subMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        int count = 0;
        //2.
        if (param != null && !param.equals("")) {
            //带参数查询
            books = bookService.searchBooksByKeyword((String) session.getAttribute("id"), param, pageNum, pageSize);
            count = bookService.countSearch(param);
            subMap.put("count", count);
            subMap.put("list", books);
            resultMap.put("data", subMap);
            resultMap.put("errorNo", "0");
            session.setAttribute("books", books);
            String resJson = JSONObject.toJSONString(resultMap);
            resp.getWriter().print(resJson);
        } else {
            //无参查询
            books =
                    bookService.searchAllBooks((String) req.getSession().getAttribute("id"), pageNum,
                            pageSize);
            count = bookService.countNum();
            subMap.put("count", count);
            subMap.put("list", books);
            resultMap.put("data", subMap);
            resultMap.put("errorNo", "0");
            //3. 将结果放入session
            req.getSession().setAttribute("books", books);
            String resJson = JSONObject.toJSONString(resultMap);
            //将count直接作为ajax请求的结果返回
            resp.getWriter().print(resJson);
        }


    }
}
